#include <iostream>
#include <functional>
#include <mutex>
#include <thread>

class Foo {
private:
//使用互斥锁
    std::mutex mtx1;
    std::mutex mtx2;
    std::mutex mtx3;

public:
    Foo() {
        mtx2.lock();
        mtx3.lock();
    }               

    void first(std::function<void()> printFirst) {
        
        // 打印 "first"
        mtx1.lock();
        printFirst();
        mtx2.unlock();
        
    }

    void second(std::function<void()> printSecond) {
       
        // 打印 "second"
        mtx2.lock();
        printSecond();
        mtx3.unlock();
        
    }

    void third(std::function<void()> printThird) {
        mtx3.lock();
        printThird();
        mtx1.unlock();
    }
};

void callFirst(Foo& foo) {
    foo.first([]{ std::cout << "first\n"; });
}

void callSecond(Foo& foo) {
    foo.second([]{ std::cout << "second\n"; });
}

void callThird(Foo& foo) {
    foo.third([]{ std::cout << "third\n"; });
}

int main() {
    Foo foo;  // 创建 Foo 类实例

    // 创建并启动三个线程，分别调用 first, second, third 方法
    std::thread t1(callFirst, std::ref(foo));
    std::thread t2(callSecond, std::ref(foo));
    std::thread t3(callThird, std::ref(foo));
   
    // 等待三个线程完成
    t1.join();
    t2.join();
    t3.join();

    return 0;
}